package com.shwread.android.qysw.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.touch_imageview.ExtendedViewPager;
import com.shwread.android.ui.widget.touch_imageview.TouchImageView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.callback.ActionListener;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.AtlasColumnInfoNew;
import logic.bean.AtlasInfo;
import logic.constants.DefaultConsts;
import logic.util.ImageLoaderUtil;
import logic.util.NetworkUtil;
import logic.util.Util;


/**
 * 图集详情页
 */
public class AtlasSeeActivity extends BaseBusinessActivity implements OnClickListener {
    public static final String FROM_TYPE = "fromType";
    public static final String IMAGE_COUNT = "image_count";
    private Context context;
    private BaseBusinessActivity bActivity;
    private ExtendedViewPager mViewPager;
    private TextView mCount, mTitle, mIntro;
    private Button mBackBtn;
    private List<AtlasInfo> atlasList;
    private RelativeLayout titleLay, introLay;
    private LinearLayout loadingLay;
    private DisplayImageOptions imageOptions;

    private AtlasColumnInfoNew resultInfo;
    private long atlasId;
    private int comeInPosition = 0;            //刚进来的position，从0开始
    private int currentPage = 1;            //刚进来的页码，从1开始
    private int totalPage = 1;            //总页数
    private int pageNumber = 20;           //一页的条数
    private int totalNumber;                   //总条数
    private final int EARLIER_COUNT = 3;            //提早几个加载下一页
    private boolean isloading = false;        //是否加载中
    private int From_Tag;                      //从哪个页面过来
    private boolean isShow = true;         //是否加载完成
    private boolean isRefresh = false;        //false 为从瀑布流过来，true 为加载更多

    private MyViewPagerAdapter adapter;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ENTERPRISE:
                    //如果是从企业专区过来
                    if (atlasList != null && atlasList.size() > 0) atlasList.clear();
                    if (resultInfo != null && resultInfo.getAtlasList() != null && resultInfo.getAtlasList().size() > 0) {
                        atlasList.addAll(resultInfo.getAtlasList());
                        mViewPager.setAdapter(adapter);
                        //显示第一张图片的信息
                        mCount.setText(1 + "/" + totalNumber);
                        mTitle.setText(atlasList.get(0).getImageName());
                        mIntro.setText(atlasList.get(0).getLongDesc());
                        mViewPager.setCurrentItem(0);
                        adapter.notifyDataSetChanged();

                    }
                    break;
                case DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ATLAS:
                    if (isRefresh == false) { //从瀑布流过来，需要显示首张图片的信息
                        if (atlasList != null && atlasList.size() > 0) { //显示图片的信息
                            mViewPager.setAdapter(adapter);
                            mCount.setText(comeInPosition + 1 + "/" + totalNumber);
                            mTitle.setText(atlasList.get(comeInPosition).getImageName());
                            //mIntro.setText(atlasList.get(comeInPosition).getLongDesc());
                            mIntro.setText(atlasList.get(comeInPosition).getShortDesc());
                            mViewPager.setCurrentItem(comeInPosition);
                            adapter.notifyDataSetChanged();
                        }
                    } else { // 加载更多成功后的操作
                        if (resultInfo != null && resultInfo.getAtlasList() != null && resultInfo.getAtlasList().size() > 0) {
                            atlasList.addAll(resultInfo.getAtlasList());
                            //																		mViewPager.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            mCount.setText(comeInPosition + "/" + atlasList.size());
                            isloading = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atlas_see_layout);
        context = this;
        bActivity = this;

        findView();
        initData();
        initListener();
    }

    private void initListener() {
        mViewPager.setOnPageChangeListener(new PageChangeListener());
        mBackBtn.setOnClickListener(this);
    }

    private void findView() {

        titleLay = (RelativeLayout) findViewById(R.id.atlas_see_title_lay);
        mBackBtn = (Button) findViewById(R.id.atlas_see_title_back);
        introLay = (RelativeLayout) findViewById(R.id.atlas_see_intro_lay);
        mCount = (TextView) findViewById(R.id.atlas_see_title_count);
        mTitle = (TextView) findViewById(R.id.atlas_see_title_name);
        mTitle.setVisibility(View.GONE);
        mIntro = (TextView) findViewById(R.id.atlas_see_intro);
        mViewPager = (ExtendedViewPager) findViewById(R.id.atlas_see_vp);
        loadingLay = (LinearLayout) findViewById(R.id.atlas_see_loading);
    }

    @SuppressWarnings("unchecked")
    private void initData() {

        atlasList = new ArrayList<AtlasInfo>();
        adapter = new MyViewPagerAdapter();

        //图片加载的配置，设置只放SD卡不放到内存里
        imageOptions = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).cacheOnDisk(true).cacheInMemory(false).build();

        //获取Intent的Extras
        From_Tag = getIntent().getExtras().getInt(FROM_TYPE);
        if (From_Tag == DefaultConsts.TAG_FROM_ATLAS) {
            atlasId = getIntent().getExtras().getLong(AtlasActivity.ATLAS_ID, 3L);
            atlasList = (List<AtlasInfo>) getIntent().getExtras().getSerializable("atlasInfos");//父页已经有的数据列表,如果没有将会去加载第一页数据
            comeInPosition = getIntent().getExtras().getInt("position", 0);//刚进来的position
            currentPage = getIntent().getExtras().getInt("currentPage", 1); //刚进来的页码
            totalPage = getIntent().getExtras().getInt("totalPage", 1); //总页数
            pageNumber = getIntent().getExtras().getInt("pageNumber", 20);//一页的条数
            totalNumber = getIntent().getExtras().getInt("totalNumber", atlasList.size());//总条数
            isRefresh = false;
            handler.sendEmptyMessage(DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ATLAS);
        } else if (From_Tag == DefaultConsts.TAG_FROM_ENTERPRISE) { //从企业专区过来，需要调接口请求数据
            atlasId = getIntent().getExtras().getLong(AtlasActivity.ATLAS_ID, 3L);
            if (NetworkUtil.isNetAvailable(bActivity)) {
                //				new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener()).start();
                NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler());
            } else {
                new NoNetDialog(bActivity).show();
            }
        }

        //刚进详情页已经是需要加载状态时加载下一页数据 或者 刚进来没有 list数据时
        if (comeInPosition > (atlasList.size() - EARLIER_COUNT) && currentPage < totalPage) {
            if (NetworkUtil.isNetAvailable(bActivity)) {
                if (!isloading) {
                    isloading = true;
                    //TODO 此处调用下一页的网络数据
                    currentPage++;
                    //					new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener2()).start();
                    NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler2());
                }
            } else {
                new NoNetDialog(bActivity).show();
            }
            if (0 == atlasList.size()) {
                loadingLay.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ViewPager滑动监听器
     */
    private class PageChangeListener
            implements
            OnPageChangeListener {
        //		private int curCount = comeInPosition;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            if (atlasList != null && atlasList.size() > 0 && arg0 == 0)//当滚动停止时刷新文字
            {
                mTitle.setText(atlasList.get(comeInPosition).getImageName());
                mIntro.setText(atlasList.get(comeInPosition).getShortDesc());//
                //				mIntro.setText(atlasList.get(comeInPosition).getLongDesc());
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            comeInPosition = arg0;
            mCount.setText((comeInPosition + 1) + "/" + totalNumber);
            if (comeInPosition >= (atlasList.size() - EARLIER_COUNT) && currentPage <= totalPage) {
                if (NetworkUtil.isNetAvailable(bActivity)) {
                    if (!isloading) {
                        isloading = true;
                        //TODO 此处调用下一页的网络数据
                        //new XXXXX接口
                        //	testDataInit(++currentPage, pageNumber);//测试延迟1s
                        //						new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener2()).start();
                        NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler2());
                    }
                }
                /*
                 * else
				 * {
				 * new NoNetDialog(bActivity).show();
				 * }
				 */
            }
        }
    }

    private class getAtlasInfoActionHandler
            extends
            ObjectHttpResponseHandler<AtlasColumnInfoNew> {

        @Override
        public void onFailure(final int statusCode, Header[] headers, String responseString, Throwable throwable) {
            //			Message msg = Message.obtain();
            //			msg.what = 101;
            //			msg.obj = message;
            //			handler.sendMessage(msg);
            isloading = false;
            if (statusCode == ResultCode.E_3003) {
                Util.showToast(context, ResultCode.getResultText(statusCode));
            }

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, AtlasColumnInfoNew object, String responseString) {
            isloading = false;
            resultInfo = object;
            totalPage = resultInfo.getTotalPage();
            totalNumber = resultInfo.getTotalNum();
            currentPage++;
            handler.sendEmptyMessage(DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ENTERPRISE);

        }

        @Override
        public Type getType() {
            return new TypeToken<AtlasColumnInfoNew>() {
            }.getType();
        }

    }

    //从企业专区进来首次调用接口的监听事件
    private class getAtlasInfoActionListener
            implements
            ActionListener {

        @Override
        public void OK(Object obj) {
            isloading = false;
            resultInfo = (AtlasColumnInfoNew) obj;
            totalPage = resultInfo.getTotalPage();
            totalNumber = resultInfo.getTotalNum();
            currentPage++;
            handler.sendEmptyMessage(DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ENTERPRISE);
        }

        @Override
        public void ERROR(final int resultCode, String message) {
            //			Message msg = Message.obtain();
            //			msg.what = 101;
            //			msg.obj = message;
            //			handler.sendMessage(msg);
            if (resultCode == ResultCode.E_3003) {
                bActivity.getUIHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        isloading = false;
                        Util.showToast(context, ResultCode.getResultText(resultCode));
                    }
                });
            }
        }

        @Override
        public void HTTPERROR(int statusCode) {
            isloading = false;
        }

    }

    private class getAtlasInfoActionHandler2
            extends
            ObjectHttpResponseHandler<AtlasColumnInfoNew> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            //			Message msg = Message.obtain();
            //			msg.what = 101;
            //			msg.obj = message;
            //			handler.sendMessage(msg);

            isloading = false;
            if (statusCode == ResultCode.E_3003) {
                Util.showToast(context, ResultCode.getResultText(statusCode));
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, AtlasColumnInfoNew object, String responseString) {
            //			isloading = false;
            resultInfo = object;
            currentPage++;
            isRefresh = true;
            handler.sendEmptyMessage(DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ATLAS);

        }

        @Override
        public Type getType() {
            return new TypeToken<AtlasColumnInfoNew>() {
            }.getType();
        }

    }

    //刷新时调用接口时的监听事件
    private class getAtlasInfoActionListener2
            implements
            ActionListener {

        @Override
        public void OK(Object obj) {
            //			isloading = false;
            resultInfo = (AtlasColumnInfoNew) obj;
            currentPage++;
            isRefresh = true;
            handler.sendEmptyMessage(DefaultConsts.SHOW_ATLAS_DETAIL_FROM_ATLAS);
        }

        @Override
        public void ERROR(final int resultCode, String message) {
            //			Message msg = Message.obtain();
            //			msg.what = 101;
            //			msg.obj = message;
            //			handler.sendMessage(msg);

            if (resultCode == ResultCode.E_3003) {
                bActivity.getUIHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        isloading = false;
                        Util.showToast(context, ResultCode.getResultText(resultCode));
                    }
                });
            }
        }

        @Override
        public void HTTPERROR(int statusCode) {
            isloading = false;
        }

    }

    class ViewHolder {
        LinearLayout loading_lay, loadFail_lay;
        TouchImageView img;
    }

    class MyViewPagerAdapter
            extends
            PagerAdapter {

        @Override
        public int getCount() {
            return atlasList.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, final int position) {
            final ViewHolder holder;
            View view = null;
            holder = new ViewHolder();
            view = LayoutInflater.from(context).inflate(R.layout.atlas_see_item, (ViewGroup) bActivity.findViewById(R.layout.atlas_see_layout));
            holder.loading_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loading);
            holder.loadFail_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loadfail);
            holder.img = (TouchImageView) view.findViewById(R.id.atlas_see_item_img);
            //加载图片
            if (NetworkUtil.isNetAvailable(bActivity)) {
                if (logic.util.Util.isNotEmpty(atlasList.get(position).getImageUrl())) {
                    ImageLoaderUtil.loadWebUrl(atlasList.get(position).getImageUrl(), holder.img, imageOptions, new MyImageLoadingListener(holder));
                } else { //显示默认图片
                    String s1 = atlasList.get(position).getImageUrl();
                    //					holder.img.setBackgroundResource(R.drawable.atlas_see_item_loading_fail);
                    holder.img.setImageResource(R.drawable.atlas_see_item_loading_fail);
                }
            } else {
                new NoNetDialog(bActivity).show();
            }

            holder.img.setOnClickListener(AtlasSeeActivity.this);
            holder.loading_lay.setOnClickListener(AtlasSeeActivity.this);

            //失败点击重新加载
            holder.loadFail_lay.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (NetworkUtil.isNetAvailable(bActivity)) {
                        if (logic.util.Util.isNotEmpty(atlasList.get(position).getImageUrl())) {
                            ImageLoaderUtil.loadWebUrl(atlasList.get(position).getImageUrl(), holder.img, imageOptions, new MyImageLoadingListener(holder));
                        } else { //显示默认图片
                            //							holder.loading_lay.setVisibility(View.GONE);
                            //							holder.loadFail_lay.setVisibility(View.VISIBLE);
                            //							holder.img.setVisibility(View.GONE);
                            holder.img.setBackgroundResource(R.drawable.atlas_see_item_loading_fail);
                        }
                    } else {
                        new NoNetDialog(bActivity).show();
                    }
                }
            });

            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.atlas_see_title_back:
                this.onBackPressed();
                break;
            case R.id.atlas_see_item_img:
                detailManager();
                break;
            case R.id.atlas_see_item_loading:
                detailManager();
                break;
        }
    }

    /**
     * 管理上下内容的显示
     */
    private void detailManager() {
        if (isShow) {
            hideDetail();
        } else {
            showDetail();
        }
    }

    private void hideDetail() {
        Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_out);
        titleLay.setAnimation(animationTop);
        animationTop.start();
        Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_out);
        introLay.setAnimation(animationBottom);
        animationBottom.start();
        titleLay.setVisibility(View.GONE);
        introLay.setVisibility(View.GONE);
        isShow = false;
    }

    //显示图片细节，上下透明度
    private void showDetail() {
        titleLay.setVisibility(View.VISIBLE);
        introLay.setVisibility(View.VISIBLE);
        Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_in);
        titleLay.setAnimation(animationTop);
        animationTop.start();
        Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_in);
        introLay.setAnimation(animationBottom);
        animationBottom.start();
        isShow = true;
    }

    /**
     * 图片加载监听器
     */
    class MyImageLoadingListener
            implements
            ImageLoadingListener {
        private ViewHolder holder;

        public MyImageLoadingListener(ViewHolder holder) {
            this.holder = holder;
        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            updateLoadingView(1, holder);
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            updateLoadingView(-1, holder);
        }

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
            updateLoadingView(0, holder);
        }

    }

    /**
     * @param state 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int state, ViewHolder holder) {
        switch (state) {
            case 0:
                holder.loading_lay.setVisibility(View.VISIBLE);
                holder.loadFail_lay.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                break;
            case 1:
                holder.loading_lay.setVisibility(View.GONE);
                holder.loadFail_lay.setVisibility(View.GONE);
                holder.img.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(context, R.anim.common_top_in);
                holder.img.setAnimation(animation);
                animation.start();
                break;
            case -1:
                holder.loading_lay.setVisibility(View.GONE);
                holder.loadFail_lay.setVisibility(View.VISIBLE);
                holder.img.setVisibility(View.GONE);
                break;
        }
    }

}
